const { ipcMain, dialog } = require('electron');
const fs = require('fs').promises;
const fsSync = require('fs');
const path = require('path');
const ExcelJS = require('exceljs');
const csv = require('csv-parser');
const crypto = require('crypto'); // 用于计算表头指纹
const FormTableParser = require('../services/FormTableParser');

function registerFileHandlers() {
    // 1. 选择导出路径
    ipcMain.handle('select-export-path', async () => {
        const result = await dialog.showOpenDialog({
            properties: ['openDirectory', 'createDirectory']
        });
        return result.canceled ? null : result.filePaths[0];
    });

    // 2. 选择导入文件 (支持多选)
    ipcMain.handle('select-import-file', async (event, options = {}) => {
        const result = await dialog.showOpenDialog({
            title: options.title || '选择文件 (支持多选)',
            properties: ['openFile', 'multiSelections'], // 开启多选
            filters: options.filters || []
        });
        return result; // 返回完整对象 { canceled, filePaths }
    });

    // 3. 选择保存文件
    ipcMain.handle('select-save-file', async (event, options = {}) => {
        const result = await dialog.showSaveDialog({
            title: options.title || '保存文件',
            defaultPath: options.defaultPath,
            filters: options.filters || []
        });
        return result.canceled ? null : result.filePath;
    });

    // 选择目录
    ipcMain.handle('select-directory', async (event, options = {}) => {
        const result = await dialog.showOpenDialog({
            title: options.title || '选择文件夹',
            properties: ['openDirectory', 'createDirectory']
        });
        return result.canceled ? null : result.filePaths[0];
    });

    // 4. 读取文本文件
    ipcMain.handle('read-text-file', async (event, filePath) => {
        return await fs.readFile(filePath, 'utf8');
    });

    // 5. [新增] 嗅探文件结构 (读取表头和预览数据)
    ipcMain.handle('inspect-files', async (event, filePaths) => {
        const results = [];
        console.log(`[Inspector] 开始扫描 ${filePaths.length} 个文件...`);

        for (const filePath of filePaths) {
            const ext = path.extname(filePath).toLowerCase();
            const fileName = path.basename(filePath);

            try {
                if (ext === '.xlsx' || ext === '.xls') {
                    const workbook = new ExcelJS.Workbook();
                    await workbook.xlsx.readFile(filePath);

                    workbook.eachSheet((worksheet, sheetId) => {
                        // 检测是否为表单式布局（如公安个人信息表）
                        const isFormStyle = FormTableParser.isFormStyleLayout(worksheet);

                        if (isFormStyle) {
                            console.log(`[Inspector] ${fileName} - Sheet "${worksheet.name}" detected as FORM-STYLE`);
                            const formData = FormTableParser.parseFormStyleSheet(worksheet);
                            const standardData = FormTableParser.convertToPreviewFormat(formData);
                            const displayNames = FormTableParser.getHeaderDisplayNames();

                            // 生成表头（排除extra_data）
                            const fieldKeys = Object.keys(standardData).filter(k => k !== 'extra_data');
                            const displayHeaders = fieldKeys.map(k => displayNames[k] || k);

                            // 创建预览数据行
                            const previewRow = {};
                            fieldKeys.forEach(k => {
                                previewRow[displayNames[k] || k] = standardData[k] || '';
                            });

                            const signature = crypto.createHash('md5').update(fieldKeys.join('|')).digest('hex');

                            results.push({
                                filePath,
                                fileName,
                                sheetName: worksheet.name,
                                headers: displayHeaders,
                                signature: signature,
                                rowCount: 1,
                                preview: [previewRow],
                                isFormStyle: true,
                                formData: standardData
                            });
                            return; // 跳过常规处理
                        }

                        // 常规表格处理
                        const firstRow = worksheet.getRow(1);
                        const headers = [];
                        const headerMap = {};

                        firstRow.eachCell((cell, colNumber) => {
                            const val = cell.value ? cell.value.toString().trim() : '';
                            if (val) {
                                headers.push(val);
                                headerMap[colNumber] = val;
                            }
                        });

                        if (headers.length > 0) {
                            const headerStr = headers.join('|');
                            const signature = crypto.createHash('md5').update(headerStr).digest('hex');

                            // 读取前10行数据作为预览
                            const preview = [];
                            const maxPreviewRows = 10;
                            let rowsRead = 0;

                            worksheet.eachRow((row, rowNumber) => {
                                if (rowNumber === 1) return; // Skip header
                                if (rowsRead >= maxPreviewRows) return;

                                const rowData = {};
                                let hasData = false;

                                row.eachCell((cell, colNumber) => {
                                    const header = headerMap[colNumber];
                                    if (header) {
                                        let value = cell.value;
                                        if (value !== null && value !== undefined) {
                                            if (typeof value === 'object') {
                                                if (value instanceof Date) {
                                                    // Use UTC methods to avoid timezone issues
                                                    const year = value.getUTCFullYear();
                                                    if (year === 1899 || year === 1900) {
                                                        // Time-only value
                                                        const h = String(value.getUTCHours()).padStart(2, '0');
                                                        const m = String(value.getUTCMinutes()).padStart(2, '0');
                                                        const s = String(value.getUTCSeconds()).padStart(2, '0');
                                                        value = `${h}:${m}:${s}`;
                                                    } else {
                                                        const hasTime = value.getUTCHours() !== 0 || value.getUTCMinutes() !== 0 || value.getUTCSeconds() !== 0;
                                                        const y = value.getUTCFullYear();
                                                        const mo = String(value.getUTCMonth() + 1).padStart(2, '0');
                                                        const d = String(value.getUTCDate()).padStart(2, '0');
                                                        if (hasTime) {
                                                            const hh = String(value.getUTCHours()).padStart(2, '0');
                                                            const mi = String(value.getUTCMinutes()).padStart(2, '0');
                                                            const se = String(value.getUTCSeconds()).padStart(2, '0');
                                                            value = `${y}-${mo}-${d} ${hh}:${mi}:${se}`;
                                                        } else {
                                                            value = `${y}-${mo}-${d}`;
                                                        }
                                                    }
                                                }
                                                else if (value.text) value = value.text;
                                                else if (value.result !== undefined) value = value.result;
                                                else if (value.richText) value = value.richText.map(t => t.text).join('');
                                            }
                                            const strVal = String(value).trim();
                                            if (strVal !== '') {
                                                rowData[header] = strVal;
                                                hasData = true;
                                            }
                                        }
                                    }
                                });

                                if (hasData) {
                                    preview.push(rowData);
                                    rowsRead++;
                                }
                            });

                            console.log(`[Inspector] ${fileName} - Headers: ${headers.length}, Preview: ${preview.length} rows`);

                            results.push({
                                filePath,
                                fileName,
                                sheetName: worksheet.name,
                                headers: headers,
                                signature: signature,
                                rowCount: worksheet.rowCount,
                                preview: preview
                            });
                        }
                    });
                } else if (ext === '.csv') {
                    await new Promise((resolve) => {
                        const preview = [];
                        const stream = fsSync.createReadStream(filePath).pipe(csv());
                        let headers = [];
                        let rowCount = 0;
                        const maxPreviewRows = 10;

                        stream.on('headers', (headerList) => {
                            headers = headerList.map(h => h.trim()).filter(h => h);
                        });

                        stream.on('data', (data) => {
                            if (rowCount < maxPreviewRows) {
                                preview.push(data);
                                rowCount++;
                            } else {
                                stream.destroy();
                            }
                        });

                        stream.on('close', () => {
                            if (headers.length > 0) {
                                const signature = crypto.createHash('md5').update(headers.join('|')).digest('hex');
                                console.log(`[Inspector] ${fileName} (CSV) - Headers: ${headers.length}, Preview: ${preview.length} rows`);
                                results.push({
                                    filePath,
                                    fileName,
                                    sheetName: 'CSV',
                                    headers: headers,
                                    signature: signature,
                                    rowCount: rowCount,
                                    preview: preview
                                });
                            }
                            resolve();
                        });

                        stream.on('error', (err) => {
                            console.error('CSV读取错误:', err);
                            resolve();
                        });

                        stream.on('end', resolve);
                    });
                }
            } catch (e) {
                console.error(`嗅探失败: ${filePath}`, e);
                results.push({ filePath, fileName, error: e.message });
            }
        }
        return results;
    });

    // 6. 解析文件 (全量读取，支持指定Sheet)
    ipcMain.handle('parse-file', async (event, { filePath, dataType, options }) => {
        options = options || {};
        const targetSheetName = options.sheetName;

        try {
            const ext = path.extname(filePath).toLowerCase();
            const results = [];
            let headers = [];

            if (ext === '.xlsx' || ext === '.xls') {
                const workbook = new ExcelJS.Workbook();
                await workbook.xlsx.readFile(filePath);

                let worksheet;
                if (targetSheetName) {
                    worksheet = workbook.getWorksheet(targetSheetName);
                } else {
                    worksheet = workbook.worksheets.find(ws => ws.state === 'visible') || workbook.getWorksheet(1);
                }

                if (!worksheet) {
                    return { success: false, message: `找不到工作表: ${targetSheetName || '默认'}` };
                }

                // 检测是否为表单式布局
                const isFormStyle = FormTableParser.isFormStyleLayout(worksheet);

                if (isFormStyle) {
                    console.log(`[Parser] Form-style layout detected for ${filePath}`);
                    const formData = FormTableParser.parseFormStyleSheet(worksheet);
                    const standardData = FormTableParser.convertToPreviewFormat(formData);

                    // 返回单条数据
                    return {
                        success: true,
                        fullData: [standardData],
                        previewData: [standardData],
                        availableFields: Object.keys(standardData),
                        totalRecords: 1,
                        isFormStyle: true
                    };
                }

                const headerMap = {};
                const headerRow = worksheet.getRow(1);
                headerRow.eachCell((cell, colNumber) => {
                    const val = cell.value ? cell.value.toString().trim() : '';
                    if (val) {
                        headerMap[colNumber] = val;
                        headers.push(val);
                    }
                });

                worksheet.eachRow((row, rowNumber) => {
                    if (rowNumber === 1) return;
                    const rowData = {};
                    let hasData = false;
                    row.eachCell((cell, colNumber) => {
                        const header = headerMap[colNumber];
                        if (header) {
                            let value = cell.value;
                            if (value !== null && value !== undefined) {
                                if (typeof value === 'object') {
                                    if (value instanceof Date) value = value.toISOString();
                                    else if (value.text) value = value.text;
                                    else if (value.result !== undefined) value = value.result;
                                    else if (value.richText) value = value.richText.map(t => t.text).join('');
                                }
                                const strVal = String(value).trim();
                                if (strVal !== '') {
                                    rowData[header] = strVal;
                                    hasData = true;
                                }
                            }
                        }
                    });
                    if (hasData) results.push(rowData);
                });
            } else if (ext === '.csv') {
                await new Promise((resolve, reject) => {
                    fsSync.createReadStream(filePath).pipe(csv())
                        .on('headers', h => headers = h)
                        .on('data', data => results.push(data))
                        .on('end', resolve)
                        .on('error', reject);
                });
            } else {
                return { success: false, message: `不支持的文件格式: ${ext}` };
            }

            return {
                success: true,
                fullData: results,
                previewData: results.slice(0, 50),
                availableFields: headers,
                totalRecords: results.length
            };

        } catch (error) {
            console.error('File parse error:', error);
            return { success: false, message: `解析失败: ${error.message}` };
        }
    });

    // 导出数据
    ipcMain.handle('export-data', async (event, { data, filePath, dataType }) => {
        try {
            const workbook = new ExcelJS.Workbook();
            const worksheet = workbook.addWorksheet(dataType || 'Sheet1');

            if (!data || data.length === 0) {
                await workbook.xlsx.writeFile(filePath);
                return { success: true };
            }

            const keys = Object.keys(data[0]);
            worksheet.addRow(keys);
            worksheet.getRow(1).font = { bold: true };

            data.forEach(item => {
                const row = [];
                keys.forEach(key => row.push(item[key]));
                worksheet.addRow(row);
            });

            await workbook.xlsx.writeFile(filePath);
            return { success: true };
        } catch (error) {
            return { success: false, message: error.message };
        }
    });
}

module.exports = { registerFileHandlers };